package com.yj.springbootmiaosha.controller;

import com.yj.springbootmiaosha.redisLock.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;

@RestController
@Slf4j
public class RedisLockController {

    @Resource
    private RedisTemplate redisTemplate;

    static String key = "redisLock";
    static String value = UUID.randomUUID().toString();

    @GetMapping("redisLock")
    public String redisLock() throws InterruptedException {
        log.info("我进入了方法！");
        //获取锁
        RedisLock redisLock = new RedisLock(redisTemplate, key, 30);
        try {
            if (redisLock.getLock()) {
                log.info("我获取到了锁！");
                //模拟业务处理时间
                Thread.sleep(10000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            boolean result = redisLock.unLock();
            log.info("锁释放的结果：{}", result);
        }
        log.info("方法执行完成！");
        return "方法执行完成";
    }

}
